package com.huizluo.module4.chatroom;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class ServerThead extends Thread{
    private Room room;
    private User user;

    public ServerThead(User user,Room room) {
        this.user = user;
        this.room = room;
    }

    @Override
    public void run() {
        ObjectInputStream or = null;

        while (true){
            try{
                if (this.user.getConn().isClosed()){
                    System.out.println("client " + this.user.getId() + " close");
                    break;
                }
                or = new ObjectInputStream(this.user.getConn().getInputStream());
                Message msg = (Message) or.readObject();
                msg.setUserID(this.user.getId());
                System.out.println("recv client msg " + new String(msg.getData()));

                this.room.SendMsgToAll(this.user,msg);

                //发送文件
                if (msg.getType() == 1){
                    DataInputStream ds = new DataInputStream(this.user.getConn().getInputStream());
                    String fileName = ds.readUTF();
                    this.room.SendFileName(user,fileName);
                    long fileLength = ds.readLong();
                    this.room.SendFileLength(user,fileLength);
                    int len = 0;
                    byte[] bytes = new byte[8*1024];
                    while ((len = ds.read(bytes,0,bytes.length))!=-1){
                        this.room.SendFileToAll(user,bytes,len);
                    }
                    System.out.println("文件传输完成");
                }

            }catch (IOException | ClassNotFoundException e){
                break;
            }
        }

        try {
            if (null != or) {
                or.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
